package receivers;

import services.CreatRoomService;
import tw.edu.tku.im.maze.AddRoomRep;
import tw.edu.tku.im.maze.RepPacket;
import tw.edu.tku.im.maze.TimeOutRep;

import com.example.maze.ConnectionInfo;
import com.example.maze.LobbyActivity;
import com.example.maze.RoomActivity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class CreatRoomRepReceiver extends BroadcastReceiver {
   Activity currentUIActivity;
   
   //[ -------------------- construct --------------------
   public CreatRoomRepReceiver(Activity activity) {
      currentUIActivity= activity;
   }
   //] -------------------- construct --------------------
   
   // --------------------------------------------------
   private void goToNextActivity(Context context) {
      Intent intent= new Intent(context, RoomActivity.class);
      intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      context.startActivity(intent);
   }
   @Override
   public void onReceive(Context context, Intent intent) {  
//android.util.Log.d("DebugMsg", "CreatRoomRepReceiver catch!");      
      ((LobbyActivity)currentUIActivity).dismissMyDialog();
      RepPacket rep= (RepPacket)intent.getParcelableExtra(CreatRoomService.PACKET);
      ConnectionInfo.identity= ConnectionInfo.HE_IS_CLIENT;
      
      if(rep instanceof TimeOutRep) {         
         ((LobbyActivity)currentUIActivity).showMsgDialog("連線逾時");
      } else {
         AddRoomRep mAddRoomRep= (AddRoomRep)rep;
         if(mAddRoomRep.getState() == 0) {
            ConnectionInfo.parseAndSaveInfo(mAddRoomRep);
            ConnectionInfo.identity= ConnectionInfo.HE_IS_HOST;
            goToNextActivity(context);
         } else if(mAddRoomRep.getState() == 1) {
            ((LobbyActivity)currentUIActivity).showMsgDialog("開啟失敗");
         }
      }
   }
   // --------------------------------------------------
}
